package LeetCode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class LC_594_LongestHarmoniousSubsequence {

    public static void main(String[] args) {

    }

    public class Solution {
        public int findLHS(int[] nums) {
            if (nums.length < 1) return 0;
            Arrays.sort(nums);
            Map<Integer, Integer> map = new LinkedHashMap<>();
            for (int num : nums) {
                if (map.get(num) == null) {
                    map.put(num, 1);
                } else {
                    int temp = map.get(num);
                    map.put(num, temp + 1);
                }
            }
            int beforeKey = 0;
            int beforeValue = 0;
            int result = 0;
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                if (beforeValue == 0) {
                    beforeKey = entry.getKey();
                    beforeValue = entry.getValue();
                } else {
                    if (entry.getKey() - beforeKey == 1)
                        result = Math.max(beforeValue + entry.getValue(), result);
                    beforeKey = entry.getKey();
                    beforeValue = entry.getValue();
                }
            }
            return result;
        }
    }

    public class Solution_2 {
        public int findLHS(int[] nums) {
            Map<Integer, Integer> map = new HashMap<>();
            for (int num : nums) {
                map.put(num, map.getOrDefault(num, 0) + 1);
            }
            int max = 0;
            for (int num : map.keySet()) {
                if (map.containsKey(num + 1)) {
                    int tmp = map.get(num) + map.get(num + 1);
                    max = Math.max(max, tmp);
                }
            }
            return max;
        }
    }
}